package com.mujin.keji.collectionsystem.module.mypager.views;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.module.main.dto.SavePhoneDto;
import com.mujin.keji.collectionsystem.module.main.viewmodel.MainViewModel;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.module.mypager.viewmodel.UserViewModel;
import com.mujin.keji.collectionsystem.utils.DeviceUtils;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.RxTimerUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;


/**
 * 修改本机号码
 *
 * @author weishixiong
 * @Time 2018-06-20
 */

public class ValidationMyPhoneActivity extends BaseActivity implements View.OnClickListener {
    private EditText etPhone;
    private EditText etCode;
    private TextView tvGetMsg;
    private Button btnOk;
    private MainViewModel mainViewModel;
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_validationmyphone;
    }

    @Override
    public void initView() {
        setCenterTitle("验证本机号码", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etCode = (EditText) findViewById(R.id.et_code);
        tvGetMsg = (TextView) findViewById(R.id.tv_get_msg);
        btnOk = (Button) findViewById(R.id.btn_ok);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    tvGetMsg.setBackgroundResource(R.drawable.shape_get_msg_normal);
                    tvGetMsg.setTextColor(getResources().getColor(R.color.color_main_title));
                    tvGetMsg.setEnabled(true);
                } else {
                    tvGetMsg.setBackgroundResource(R.drawable.shape_get_msg_dark);
                    tvGetMsg.setTextColor(getResources().getColor(R.color.color_text_dark));
                    tvGetMsg.setEnabled(false);
                }
                if (EmptyUtils.isNotEmpty(etCode.getText().toString()) && EmptyUtils.isNotEmpty(etPhone.getText().toString())) {
                    btnOk.setEnabled(true);
                    btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                } else {
                    btnOk.setEnabled(false);
                    btnOk.setBackgroundResource(R.drawable.shape_button_enable);
                }
            }
        });
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (EmptyUtils.isNotEmpty(etCode.getText().toString()) && EmptyUtils.isNotEmpty(etPhone.getText().toString())) {
                    btnOk.setEnabled(true);
                    btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                } else {
                    btnOk.setEnabled(false);
                    btnOk.setBackgroundResource(R.drawable.shape_button_enable);
                }
            }
        });
        tvGetMsg.setOnClickListener(this);
        btnOk.setOnClickListener(this);
    }

    private int time = 60;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_msg:
                getLoadingDialog().showDialog();
                userViewModel.getMsgLiveData(etPhone.getText().toString()).observe(this, new Observer<BaseDto<String>>() {
                    @Override
                    public void onChanged(@Nullable BaseDto<String> stringBaseDto) {
                        getLoadingDialog().dismiss();
                        if(stringBaseDto.getCode()==Constant.Server.SUCCESS_CODE)
                        {
                            tvGetMsg.setText(String.valueOf(time + "s"));
                            tvGetMsg.setEnabled(false);
                            tvGetMsg.setBackgroundResource(R.drawable.shape_get_msg_dark);
                            tvGetMsg.setTextColor(getResources().getColor(R.color.color_text_dark));
                            RxTimerUtil.interval(1000, new RxTimerUtil.IRxNext() {
                                @Override
                                public void doNext() {
                                    if (time == 1) {
                                        tvGetMsg.setBackgroundResource(R.drawable.shape_get_msg_normal);
                                        tvGetMsg.setTextColor(getResources().getColor(R.color.color_main_title));
                                        tvGetMsg.setEnabled(true);
                                        tvGetMsg.setText("获取验证码");
                                        RxTimerUtil.cancel();
                                        time = 60;
                                        etPhone.setEnabled(true);
                                    } else {
                                        time--;
                                        tvGetMsg.setText(String.valueOf(time + "s"));
                                        etPhone.setEnabled(false);
                                    }

                                }
                            });
                        }
                        else{
                            ToastUtils.showToast(stringBaseDto.getMsg()+"");
                        }
                    }
                });
                break;
            case R.id.btn_ok:
                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                        getLoadingDialog().dismiss();
                        DialogUtils.showPerMissionDailog(Constant.FINALVALUE.PHONE_MESSAGE, ValidationMyPhoneActivity.this);
                        return;
                    }
                    String imei = telephonyManager.getDeviceId();
                    getLoadingDialog().showDialog();
                    mainViewModel.getDtoLiveData(DeviceUtils.getUniqueId(this), imei, etPhone.getText().toString(), etCode.getText().toString()).observe(this, new Observer<BaseDto<SavePhoneDto>>() {
                        @Override
                        public void onChanged(@Nullable BaseDto<SavePhoneDto> savePhoneDtoBaseDto) {
                            getLoadingDialog().dismiss();
                            ToastUtils.showToast(savePhoneDtoBaseDto.getMsg());
                            if (savePhoneDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
                                finish();
                                startActivity(new Intent(ValidationMyPhoneActivity.this, MainActivity.class));
                            }
                        }
                    });
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }
    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            CcsApplication.logout(Constant.Server.I_LOGOUT);
            //System.exit(0);; //退出函数

        }
        return false;
    }

    @Override
    public void back(View view) {
        super.back(view);
        CcsApplication.logout(Constant.Server.I_LOGOUT);
    }
}
